//create.js
const app = getApp()
const db = wx.cloud.database()
Page({
    data: {
        scanPage: false,//本页是否为扫描模式
        isExist: false,//当前操作的发票是否已录入过
        hideInputModal: true,//是否隐藏输入模组
        hasMemo: false,
        invoice: {}
    },

    /**
     * 生命周期函数--监听页面加载
     * 1.区别手动添加和扫码添加页面
     * 2.修改本页标题为发票类型    类型对应:10-增值税电子普通发票，04-增值税普通发票，01-增值税专用发票
     * 3.查验发票
     */
    onLoad: function (options) { 
        if(options.invoice) {
            this.setInvoice(options.invoice)
        }
        if(options.id) {
            var inv = {}
            inv._id = parseInt(options.id)
            this.checkInvoice(inv)
        }
        this.setData({ scanPage: options.invoice ? true : false })
    },

    setInvoice: function(data) {
        var invoice = app.fromInitStr(data);
        var type = invoice.type;
        type = type == '10' ? '增值税电子普通发票' : type == '01' ? '增值税专用发票' : '增值税普通发票'
        wx.setNavigationBarTitle({ title: type })
        this.checkInvoice(invoice);
    },

    confirm: function() {
        let that = this
        wx.showLoading({
          title: '处理中...',
          mask: true
        })
        var now = new Date()
        this.data.invoice.update_time = now.getTime()
        this.data.invoice.status = 1
        if(this.data.isExist) {
            var inv = this.data.invoice
            var id = this.data.invoice._id
            delete inv._id
            delete inv._openid
            db.collection('invoice').doc(id).update({
                data: inv,
                success: res => {
                    wx.hideLoading({})
                    if(res.errMsg == 'document.update:ok') {
                        wx.showToast({ title: '处理完成' })
                        that.data.invoice._id = id
                        that.setData({ invoice: that.data.invoice, hasMemo: false })
                    } else {
                        app.showErrorModal('提示', '处理失败，请稍后重试', false);
                    }
                },
                fail: _res => {
                    console.log(_res)
                    wx.hideLoading({})
                    app.showErrorModal('提示', '网络异常，请稍后重试', false);
                }
            })
        } else {
            db.collection('invoice').add({
                data: that.data.invoice,
                success: res => {
                    wx.hideLoading({})
                    if(res.errMsg == 'collection.add:ok') {
                        wx.showToast({ title: '处理完成' })
                        that.setData({ invoice: that.data.invoice, hasMemo: false })
                    } else {
                        app.showErrorModal('提示', '处理失败，请稍后重试', false);
                    }
                },
                fail: _res => {
                    wx.hideLoading({})
                    app.showErrorModal('提示', '网络异常，请稍后重试', false);
                }
            })
        }
    },

    /**
     * 查验发票
     * @param {*} invoice 发票
     */
    checkInvoice: function(invoice) {
        var that = this;
        wx.showLoading({
            title: '查询中...',
            mask: true
        })
        db.collection('invoice').where({
            _id: invoice._id
        }).get({
            success: res => {
                wx.hideLoading();
                if(res.errMsg == 'collection.get:ok' && res.data.length > 0) {  // 有记录
                    res.data[0].time = app.getTime(new Date(res.data[0].update_time))
                    that.setData({ 
                        invoice: res.data[0],
                        isExist: true
                    });
                } else {  // 无记录
                    invoice.status = 0
                    that.setData({ 
                        invoice: invoice,
                        isExist: false
                    });
                }
            },
            fail: _res => {
                wx.hideLoading();
                app.showErrorModal('提示', '网络异常，请检查后重试', false);
            }
        })
    },

    /**
     * 扫描下一个
     */
    toScanNext: function() {
        let that = this
        wx.scanCode({
            success(res) {
                var result = res.result;
                if (result.split(",").length == 7 || result.split(",").length == 8 || result.split(",").length == 9) {
                    that.setInvoice(result)
                } else {
                    app.showErrorModal('异常', '暂不支持此类发票扫描添加，请手动输入', false);
                }
            },
            fail: _res => {
                app.showErrorModal('提示', '未扫描到有效的二维码', false);
            }
        })
    },

    /**
     * 限制金额框只能输入数值
     * @param {*} val 值
     */
    money(val) {
        let num = val.toString(); //先转换成字符串类型
        if (num.indexOf('.') == 0) { //第一位就是 .
            num = '0' + num
        }
        num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
        num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        if (num.indexOf(".") < 0 && num != "") {
            num = parseFloat(num);
        }
        return num
    },

    /* 事件处理函数 */
    numInput: function (e) {
        this.data.invoice._id = e.detail.value; 
    },
    numBlur: function (e) {
        if (e.detail.value != '') {
            var inv = {}
            inv._id = parseInt(e.detail.value)
            this.checkInvoice(inv)
        }
    },
    moneyInput: function (e) {
        this.data.invoice.price = this.money(e.detail.value);
    },
    remarkInput: function (e) {
        this.data.invoice.remark = e.detail.value;
        this.setData({ hasMemo: this.data.invoice.applicant != '' || this.data.invoice.remark })
    },
    peopleInput: function (e) {
        this.data.invoice.applicant = e.detail.value;
        this.setData({ hasMemo: this.data.invoice.applicant != '' || this.data.invoice.remark })
    }
})